// 螺旋矩阵
/*给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
*/
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int count = 1;
        vector<int> arr;
        int n = matrix.size();
        int m = matrix[0].size();
        int state = 1;
        int x = 0, y = 0;
        vector<vector<int>>nums;
        for(int i=0;i<n;i++)
        {
            vector<int>_nums(m,0);
            nums.push_back(_nums);
        }
        while (count != m * n) {
            if (state == 1) {
                if (y + 1 >= m || nums[x][y + 1]) {
                    state = 2;
                } else {
                    arr.push_back(matrix[x][y]);
                    nums[x][y]++;
                    y++;
                    count++;
                }
            } else if (state == 2) {

                if (x + 1 >= n ||nums[x+1][y]) {
                    state = 3;
                } else {
                    arr.push_back(matrix[x][y]);
                   nums[x][y]++;
                    x++;
                    count++;
                }
            } else if (state == 3) {

                if (y - 1 < 0 || nums[x][y-1]) {
                    state = 4;
                } else {
                    arr.push_back(matrix[x][y]);
                   nums[x][y]++;
                    y--;
                    count++;
                }
            } else if (state == 4) {
                if (x - 1 < 0 || nums[x-1][y]) {
                    state = 1;
                } else {
                    arr.push_back(matrix[x][y]);
                    nums[x][y]++;
                    x--;
                    count++;
                }
            }
        }
        arr.push_back(matrix[x][y]);
        return arr;
    }
};